package com.ruoyi.lab.service.impl;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.controller.BaseController;
import com.google.api.client.util.Joiner;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.lab.domain.JacTestProject;
import com.ruoyi.lab.mapper.JacTestProjectMapper;
import com.ruoyi.lab.mapper.JacTestResultMapper;
import com.ruoyi.lab.utils.MyTool;
import lombok.Data;
import org.ehcache.xml.model.ThreadPoolsType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lab.mapper.JacTestOutlineMapper;
import com.ruoyi.lab.domain.JacTestOutline;
import com.ruoyi.lab.service.IJacTestOutlineService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.servlet.http.HttpServletRequest;
import static com.ruoyi.common.datasource.DynamicDataSourceContextHolder.log;

/**
 * outlineService业务层处理
 * author sxx
 * date 2021-04-06
 */

@Service
public class JacTestOutlineServiceImpl extends BaseController implements IJacTestOutlineService
{
    @Autowired
    private JacTestOutlineMapper jacTestOutlineMapper;
    @Autowired
    private JacTestResultMapper jacTestResultMapper;
    @Autowired
    private JacTestProjectMapper jacTestProjectMapper;
    private static final String OK ="1";

    /**
     * 根据projectcode查询outline    供应商返回标志true
     */

    @Override
    public JacTestOutline selectJacTestOutlineById(Long projectcode)
    {
        HttpServletRequest request = ServletUtils.getRequest();
        String remark=jacTestOutlineMapper.selectRemarkById(request.getHeader(Constants.CURRENT_ID));
        JacTestOutline jacTestOutline= jacTestOutlineMapper.selectJacTestOutlineById(projectcode);
        if(null==remark||!"第三方试验室".equals(remark)){
            jacTestOutline.setFlag("false");
            return jacTestOutline;
        }else {
            jacTestOutline.setFlag("true");
            return jacTestOutline;
        }
    }

    /**
     * 查询outline列表进行页面展示
     * 传入参数 jacTestOutline outline
     * 返回参数 result
     */

    @Override
    public List<JacTestOutline> selectJacTestOutlineList(JacTestOutline jacTestOutline)
    {
        HttpServletRequest request = ServletUtils.getRequest();
        String usertype = jacTestOutlineMapper.selectUserTypeById(request.getHeader(Constants.CURRENT_ID));
        jacTestOutline.setUserid(request.getHeader(Constants.CURRENT_ID));
        if(usertype.equals("01")){
            if("第三方试验室".equals(jacTestOutlineMapper.selectSysUserRemarkByUserId(jacTestOutline.getUserid())))
                usertype="02" ;
        }
        JacTestOutline jacTestOutline2 = MyTool.selectJacTestOutLineByRequirements(jacTestOutline);
        JacTestOutline jacTestOutline1 = (JacTestOutline) jacTestOutline2.clone();
        if ("00".equals(usertype)){
            List<String> roleid=jacTestOutlineMapper.selectRoleIdByUserId(jacTestOutline1.getUserid());
            for (String S : roleid) {
                if(!("62".equals(S))) {
                    jacTestOutline1.setSubmitpeople(jacTestOutlineMapper.selectSysUserNameByUserId(jacTestOutline1.getUserid()));
                }else{
                    if(null!=jacTestOutline.getSubmitpeople()){
                        jacTestOutline1.setSubmitpeople(jacTestOutline.getSubmitpeople());
                    } else{
                        jacTestOutline1.setSubmitpeople(null);
                    }
                    break;
                }
            }
            startPage();
            return jacTestOutlineMapper.selectJacTestOutlineList(jacTestOutline1);
        } else if ("01".equals(usertype)){
            startPage();
            return jacTestOutlineMapper.selectJacTestOutlineListSupp(jacTestOutline1);
        } else {
            startPage();
            return jacTestOutlineMapper.selectJacTestOutlineListNewTest(jacTestOutline1);
        }
    }

    /**
     * 新增outline按钮
     * 传入参数 jacTestOutline outline
     * 返回结果 result
     */

    @Override
    public int insertJacTestOutline(JacTestOutline jacTestOutline)
    {   String userid=  ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
        String username=jacTestOutlineMapper.selectSysUserNameByUserId(userid);
        jacTestOutline.setSubmitpeople(username);
        return jacTestOutlineMapper.insertJacTestOutline(jacTestOutline);
    }

    /**
     * 更新outline按钮 修改outline内容
     * 传入参数 jacTestOutline
     * 返回结果  result
     */

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    @Override
    public String updateJacTestOutline(Map<String, List<JacTestOutline>>  jacTestOutline)
    {   String result=OK;
        List<String> finalString=new ArrayList<>();
        List<JacTestOutline> jacTestOutlines =  jacTestOutline.get("datas");
        try{
            for (JacTestOutline jacTestOutline1:jacTestOutlines) {
            jacTestOutlineMapper.updateJacTestOutline(jacTestOutline1);
            }
        }catch (Exception e){
            result="更新失败，请联系管理员！";
        }
        if(finalString.size()!=0) return Joiner.on(',').join(finalString);
         return result;
    }


    /**
     * 更新试验大纲附件按钮 重置outline的状态位以及相关联的project的状态位
     * 传入参数 jacTestOutline
     * 返回结果  result
     */

    @Override
    public int updateOutline (JacTestOutline jacTestOutline){
        jacTestOutline.setStatus("notbegin");
        jacTestOutline.setStage("underissue");
        jacTestOutlineMapper.setFinishTimeNUll(jacTestOutline.getProjectcode());
        List<JacTestProject> list = jacTestProjectMapper.selectJacTestProjectListPro(jacTestOutline.getProjectcode());
        for (JacTestProject j:list){
            j.setExperimentstatus("create");
            j.setPstage("beforeaudit");
            j.setExperimentresult("new");
            jacTestProjectMapper.updateJacTestProject(j);
        }
        return jacTestOutlineMapper.updateJacTestOutline(jacTestOutline);
    }

    /**
     * 删除大纲按钮
     * 删除outline对象以及其对应的project和result
     * 传入参数 Jacoutline projectcodes
     * 返回结果  result
     */

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    @Override
    public String deleteJacTestOutlineByIds(String projectcodes)
    {
        String result=OK;
        List<String> finalString=new ArrayList<>();
        Long[] a= Convert.toLongArray(projectcodes);
        try {
            for (Long s: a) {
                List<JacTestProject> jacTestProjectList=jacTestProjectMapper.selectJacTestProjectListNew(s);
                for (JacTestProject jacTestProject:jacTestProjectList) {
                    jacTestResultMapper.deleteJacTestResultBycode(jacTestProject.getId());
                }
                jacTestProjectMapper.deleteJacTestProjectByItemCode(s);
            }
            jacTestOutlineMapper.deleteJacTestOutlineByIds(Convert.toStrArray(projectcodes));
        }catch(Exception e){
            result = "删除失败，" + " 请联系管理员！";
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(result, e);
            finalString.add(result);
        }
         if(finalString.size()!=0) return   Joiner.on(',').join(finalString);
         return result;
    }

    /**
     * 根据projectcode删除outline
     */

    @Override
    public int deleteJacTestOutlineById(Long projectcode)
    {
        return jacTestOutlineMapper.deleteJacTestOutlineById(projectcode);
    }

    /**
     * 大纲发布按钮
     * 发布大纲信息
     * 传入参数 JacTestOutline projectcodes
     * 返回参数 result
     */

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    @Override
    public String submitJacTestOutline(JacTestOutline jacTestOutline)
    {

        String result=OK;
        List<String> a=new ArrayList<>();
        String[] projectcodelist = Convert.toStrArray(jacTestOutline.getProjectcodes());
        jacTestOutline.setProjectcodelist(projectcodelist);
        List<JacTestOutline> jt = jacTestOutlineMapper.selectJacTestOutlineList(jacTestOutline);
            for (JacTestOutline list : jt) {
                if ("underissue".equals(list.getStage())) {
                    result = "项目代码：" + list.getItemcode() + "已经在发布中，请勿重复发布！";
                } else {
                    try {
                        list.setStage("underissue");

                        jacTestOutlineMapper.updateJacTestOutline(list);
                    }catch (Exception e) {
                        result = "项目代码：" + list.getItemcode() + "提交失败" + "。请联系管理员!";
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        log.error(result, e);
                        a.add(result);
                    }
                }
            }
        if(a.size()>0) return Joiner.on(',').join(a);
        return result;
    }

    /**
     * 上传最终结果附件按钮
     * 生成结果附件
     * 传入参数 JacTestOutline (projectcodes、status)
     * 返回参数 result
     */

    @Override
    public String updateMyJacTestOutline(JacTestOutline jacTestOutline){
        String result=OK;
        List<JacTestProject> jacTestProjectList=jacTestProjectMapper.selectJacTestProjectByItemcode(jacTestOutline.getProjectcode());
        if(jacTestProjectList.size()==0){
            result="尚未录入试验计划，请勿提交结果附件！";
            return result;
        }
        for (JacTestProject project:jacTestProjectList) {
              if("new".equals(project.getExperimentresult())){
                  result="尚有计划未完成，请等完成所有的试验计划后再提交！";
                  return result; 
              }
        }
        jacTestOutlineMapper.updateJacTestOutline(jacTestOutline);
        return result;
    }
    @Override
    public List<JacTestOutline> selectJacTestOutlineListByVendorname(String vendorname){
        return jacTestOutlineMapper.selectJacTestOutlineListByVendorname(vendorname);
    }
}